package com.anji.plus.gaea.export.utils;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.WriterException;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.oned.Code128Writer;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.geom.RoundRectangle2D;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.util.Hashtable;

import static com.google.zxing.client.j2se.MatrixToImageWriter.toBufferedImage;

/**
 * Created by raodeming on 2021/4/27.
 */
public class QrCodeOrBarCodeUtil {

    private static Logger logger = LoggerFactory.getLogger(QrCodeOrBarCodeUtil.class);

    private static final String CHARSET = "utf-8";
    private static final String FORMAT_NAME = "JPG";
    // 二维码尺寸
    private static final int QRCODE_SIZE = 300;
    // LOGO宽度
    private static final int WIDTH = 60;
    // LOGO高度
    private static final int HEIGHT = 60;

    public static BufferedImage createImageQRCode(String content, String imgPath, int width, int height){
        Hashtable<EncodeHintType, Object> hints = new Hashtable<>();
        hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
        hints.put(EncodeHintType.CHARACTER_SET, CHARSET);
        hints.put(EncodeHintType.MARGIN, 1);
        BitMatrix bitMatrix = null;
        try {
            bitMatrix = new MultiFormatWriter().encode(content,
                    BarcodeFormat.QR_CODE, width, height, hints);
        } catch (WriterException e) {
            logger.info("QRCode error", e);
        }
        width = bitMatrix.getWidth();
        height = bitMatrix.getHeight();
        BufferedImage image = new BufferedImage(width, height,
                BufferedImage.TYPE_INT_RGB);
        for (int x = 0; x < width; x++) {
            for (int y = 0; y < height; y++) {
                image.setRGB(x, y, bitMatrix.get(x, y) ? 0xFF000000
                        : 0xFFFFFFFF);
            }
        }
        if (imgPath == null || "".equals(imgPath)) {
            return image;
        }
        // 插入图片
//        QrCodeOrBarCodeUtil.insertImage(image, imgPath, needCompress);
        return image;
    }


    /**
     * 生成条形码
     *
     * @param content
     * @param width
     * @param height
     * @return
     * @throws Exception
     */
    public static BufferedImage createImageBar(String content, int width, int height)  {
        Hashtable<EncodeHintType, String> hints = new Hashtable<>();
        hints.put(EncodeHintType.CHARACTER_SET, "utf-8");
        Code128Writer writer = new Code128Writer();
        // 编码内容, 编码类型, 宽度, 高度, 设置参数
        BitMatrix bitMatrix = null;
        try {
            bitMatrix = writer.encode(content, BarcodeFormat.CODE_128, width, height, hints);
        } catch (WriterException e) {
            logger.info("BarCode error", e);
        }
        BufferedImage image = toBufferedImage(bitMatrix);
        return insertWords(image, content, width, height);
    }

    /**
     * 条形码下面加上文字
     *
     * @param image 条形码图片
     * @param words 文字
     * @return 返回BufferedImage
     * @author fxbin
     */
    public static BufferedImage insertWords(BufferedImage image, String words, int width, int height) {
        // 新的图片，把带logo的二维码下面加上文字
        if (!StringUtils.isEmpty(words)) {
            BufferedImage newImage = new BufferedImage(width, height + 25, BufferedImage.TYPE_INT_RGB);
            Graphics2D g2d = newImage.createGraphics();
            // 抗锯齿
            setGraphics2D(g2d);
            // 设置白色
            setColorWhite(g2d);
            // 画条形码到新的面板
            g2d.drawImage(image, 0, 0, image.getWidth(), image.getHeight(), null);
            // 画文字到新的面板
            Color color = new Color(0, 0, 0);
            g2d.setColor(color);
            // 字体、字型、字号
            g2d.setFont(new Font("STSong-Light", Font.PLAIN, 18));
            //文字长度
            int strWidth = g2d.getFontMetrics().stringWidth(words);
            //总长度减去文字长度的一半  （居中显示）
            int wordStartX = (width - strWidth) / 2;
            //height + (outImage.getHeight() - height) / 2 + 12
            int wordStartY = height + 20;
            // 画文字
            g2d.drawString(words, wordStartX, wordStartY);
            g2d.dispose();
//            outImage.flush();
            return newImage;
        }
        return null;
    }

    /**
     * 设置 Graphics2D 属性  （抗锯齿）
     *
     * @param g2d Graphics2D提供对几何形状、坐标转换、颜色管理和文本布局更为复杂的控制
     */
    private static void setGraphics2D(Graphics2D g2d) {
        g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
        g2d.setRenderingHint(RenderingHints.KEY_STROKE_CONTROL, RenderingHints.VALUE_STROKE_DEFAULT);
        Stroke s = new BasicStroke(1, BasicStroke.CAP_ROUND, BasicStroke.JOIN_MITER);
        g2d.setStroke(s);
    }

    /**
     * 设置背景为白色
     *
     * @param g2d Graphics2D提供对几何形状、坐标转换、颜色管理和文本布局更为复杂的控制
     */
    private static void setColorWhite(Graphics2D g2d) {
        g2d.setColor(Color.WHITE);
        //填充整个屏幕
        g2d.fillRect(0, 0, 600, 600);
        //设置笔刷
        g2d.setColor(Color.BLACK);
    }

    /**
     * 插入LOGO
     *
     * @param source       二维码图片
     * @param imgPath      LOGO图片地址
     * @param needCompress 是否压缩
     * @throws Exception
     */
    private static void insertImage(BufferedImage source, String imgPath,
                                    boolean needCompress) throws Exception {
        File file = new File(imgPath);
        if (!file.exists()) {
            System.err.println("" + imgPath + "   该文件不存在！");
            return;
        }
        Image src = ImageIO.read(new File(imgPath));
        int width = src.getWidth(null);
        int height = src.getHeight(null);
        if (needCompress) { // 压缩LOGO
            if (width > WIDTH) {
                width = WIDTH;
            }
            if (height > HEIGHT) {
                height = HEIGHT;
            }
            Image image = src.getScaledInstance(width, height,
                    Image.SCALE_SMOOTH);
            BufferedImage tag = new BufferedImage(width, height,
                    BufferedImage.TYPE_INT_RGB);
            Graphics g = tag.getGraphics();
            g.drawImage(image, 0, 0, null); // 绘制缩小后的图
            g.dispose();
            src = image;
        }
        // 插入LOGO
        Graphics2D graph = source.createGraphics();
        int x = (QRCODE_SIZE - width) / 2;
        int y = (QRCODE_SIZE - height) / 2;
        graph.drawImage(src, x, y, width, height, null);
        Shape shape = new RoundRectangle2D.Float(x, y, width, width, 6, 6);
        graph.setStroke(new BasicStroke(3f));
        graph.draw(shape);
        graph.dispose();
    }

    /**
     * 生成二维码(内嵌LOGO)
     *
     * @param content      内容
     * @param imgPath      LOGO地址
     * @throws Exception
     * @return
     */
    public static ByteArrayOutputStream encodeQRCode(String content, String imgPath, int width, int height) throws Exception {
        BufferedImage image = QrCodeOrBarCodeUtil.createImageQRCode(content, imgPath, width, height);
//        mkdirs(destPath);
        // 先把读进来的图片放到一个ByteArrayOutputStream中，以便产生ByteArray
        ByteArrayOutputStream byteArrayOut = new ByteArrayOutputStream();
//        String file = new Random().nextInt(99999999) + ".jpg";
        try {
            ImageIO.write(image , FORMAT_NAME  , byteArrayOut);
        } catch (Exception e){
            logger.info("QRCode ByteArrayOS error", e);
        }
        return byteArrayOut;
    }

    /**
     * 生成二维码(内嵌LOGO)
     *
     * @param content  内容
     * @throws Exception
     * @return
     */
    public static ByteArrayOutputStream encodeBarCode(String content, int width, int height) throws Exception {
        BufferedImage image = QrCodeOrBarCodeUtil.createImageBar(content, width, height);
//        mkdirs(destPath);
        // 先把读进来的图片放到一个ByteArrayOutputStream中，以便产生ByteArray
        ByteArrayOutputStream byteArrayOut = new ByteArrayOutputStream();
//        String file = new Random().nextInt(99999999) + ".jpg";
        try {
            ImageIO.write(image , FORMAT_NAME  , byteArrayOut);
        } catch (Exception e){
            logger.info("BarCode ByteArrayOS error", e);
        }
        return byteArrayOut;
    }

    /**
     * 当文件夹不存在时，mkdirs会自动创建多层目录，区别于mkdir．(mkdir如果父目录不存在则会抛出异常)
     *
     * @param destPath 存放目录
     * @date 2013-12-11 上午10:16:36
     */
    public static void mkdirs(String destPath) {
        File file = new File(destPath);
        //当文件夹不存在时，mkdirs会自动创建多层目录，区别于mkdir．(mkdir如果父目录不存在则会抛出异常)
        if (!file.exists() && !file.isDirectory()) {
            file.mkdirs();
        }
    }


    public static void main(String[] args) throws Exception {
        String str = "{\"name\":\"sheet1\",\"QRCodeOrBarCode\":[\n" +
                "        {\n" +
                "            \"type\": \"QRCode\",\n" +
                "            \"content\": \"https://gaea.anji-plus.com\",\n" +
                "            \"height\": \"128\",\n" +
                "            \"width\": \"128\",\n" +
                "            \"backgroundColor\": \"#FFFFFF\",\n" +
                "            \"foregroundColor\": \"#000000\",\n" +
                "            \"ri\": 1,\n" +
                "            \"ci\": \"1\"\n" +
                "        },\n" +
                "        {\n" +
                "            \"type\": \"BarCode\",\n" +
                "            \"content\": \"6926557300360\",\n" +
                "            \"height\": \"50\",\n" +
                "            \"width\": \"450\",\n" +
                "            \"backgroundColor\": \"#FFFFFF\",\n" +
                "            \"foregroundColor\": \"#000000\",\n" +
                "            \"ri\": 1,\n" +
                "            \"ci\": \"1\"\n" +
                "        }\n" +
                "    ],\"freeze\":\"A1\",\"styles\":[{\"align\":\"center\"},{\"border\":{\"top\":[\"thin\",\"#000\"],\"bottom\":[\"thin\",\"#000\"],\"left\":[\"thin\",\"#000\"]}},{\"border\":{\"top\":[\"thin\",\"#000\"],\"bottom\":[\"thin\",\"#000\"]}},{\"border\":{\"top\":[\"thin\",\"#000\"],\"bottom\":[\"thin\",\"#000\"],\"right\":[\"thin\",\"#000\"]}},{\"border\":{\"top\":[\"thin\",\"#000\"],\"left\":[\"thin\",\"#000\"]}},{\"border\":{\"top\":[\"thin\",\"#000\"],\"right\":[\"thin\",\"#000\"]}},{\"border\":{\"bottom\":[\"thin\",\"#000\"],\"left\":[\"thin\",\"#000\"]}},{\"border\":{\"bottom\":[\"thin\",\"#000\"],\"right\":[\"thin\",\"#000\"]}},{\"border\":{\"top\":[\"thin\",\"#000\"],\"left\":[\"thin\",\"#000\"],\"bottom\":[\"thin\",\"#000\"],\"right\":[\"thin\",\"#000\"]}},{\"border\":{\"top\":[\"thin\",\"#000\"],\"left\":[\"thin\",\"#000\"],\"bottom\":[\"thin\",\"#000\"],\"right\":[\"thin\",\"#000\"]},\"align\":\"center\"},{\"border\":{\"top\":[\"thin\",\"#000\"],\"left\":[\"thin\",\"#000\"],\"bottom\":[\"thin\",\"#000\"],\"right\":[\"thin\",\"#000\"]},\"textwrap\":true},{\"textwrap\":true},{\"align\":\"right\"},{\"align\":\"center\",\"font\":{\"size\":14}},{\"font\":{\"size\":14}},{\"border\":{\"right\":[\"thin\",\"#000\"]}},{\"border\":{\"top\":[\"thin\",\"#000\"],\"left\":[\"thin\",\"#000\"],\"bottom\":[\"thin\",\"#000\"],\"right\":[\"thin\",\"#000\"]},\"align\":\"center\",\"valign\":\"top\"},{\"align\":\"center\",\"valign\":\"top\"},{\"border\":{\"top\":[\"thin\",\"#000\"],\"left\":[\"thin\",\"#000\"],\"bottom\":[\"thin\",\"#000\"],\"right\":[\"thin\",\"#000\"]},\"align\":\"center\",\"valign\":\"bottom\"},{\"align\":\"center\",\"valign\":\"bottom\"},{\"border\":{\"top\":[\"thin\",\"#000\"],\"left\":[\"thin\",\"#000\"],\"bottom\":[\"thin\",\"#000\"],\"right\":[\"thin\",\"#000\"]},\"align\":\"center\",\"valign\":\"middle\"},{\"align\":\"center\",\"valign\":\"middle\"},{\"align\":\"center\",\"font\":{\"size\":14},\"valign\":\"middle\"},{\"font\":{\"size\":14},\"valign\":\"middle\"},{\"valign\":\"bottom\"},{\"align\":\"center\",\"font\":{\"size\":14},\"valign\":\"bottom\"},{\"font\":{\"size\":14},\"valign\":\"bottom\"},{\"align\":\"center\",\"font\":{\"size\":14},\"valign\":\"top\"},{\"font\":{\"size\":14},\"valign\":\"top\"},{\"border\":{\"top\":[\"thin\",\"#000\"],\"left\":[\"thin\",\"#000\"],\"bottom\":[\"thin\",\"#000\"],\"right\":[\"thin\",\"#000\"]},\"valign\":\"middle\"},{\"valign\":\"middle\"},{\"border\":{\"top\":[\"thin\",\"#000\"],\"left\":[\"thin\",\"#000\"],\"bottom\":[\"thin\",\"#000\"],\"right\":[\"thin\",\"#000\"]},\"textwrap\":true,\"valign\":\"middle\"},{\"border\":{\"right\":[\"thin\",\"#000\"]},\"valign\":\"middle\"},{\"textwrap\":true,\"valign\":\"middle\"},{\"align\":\"right\",\"valign\":\"middle\"}],\"merges\":[\"A1:D1\",\"B4:D4\",\"B5:D5\",\"A7:A13\",\"A14:A19\",\"A20:A23\",\"A24:A26\",\"B24:D26\",\"A27:D28\",\"B18:D19\",\"B20:D23\"],\"rows\":{\"0\":{\"cells\":{\"0\":{\"text\":\"职工信息表\",\"style\":27,\"merge\":[0,3]},\"1\":{\"style\":28},\"2\":{\"style\":28},\"3\":{\"style\":28},\"4\":{\"style\":0}},\"height\":75},\"1\":{\"cells\":{\"0\":{\"text\":\"用户名\",\"style\":20},\"1\":{\"style\":29,\"text\":\"#{gaea_user_info.nickname}\"},\"2\":{\"text\":\"曾用名\",\"style\":20},\"3\":{\"text\":\"#{gaea_user_info.username}\",\"style\":29}}},\"2\":{\"cells\":{\"0\":{\"text\":\"邮箱\",\"style\":16},\"1\":{\"text\":\"#{gaea_user_info.email}\",\"style\":29},\"2\":{\"text\":\"手机号码\",\"style\":20},\"3\":{\"style\":29,\"text\":\"#{gaea_user_info.phone}\"}},\"height\":53},\"3\":{\"cells\":{\"0\":{\"text\":\"现居住地\",\"style\":20},\"1\":{\"text\":\"上海市杨浦区江浦路1000号\",\"merge\":[0,2],\"style\":29},\"2\":{\"style\":30},\"3\":{\"style\":30}}},\"4\":{\"cells\":{\"0\":{\"text\":\"户口所在地\",\"style\":20},\"1\":{\"text\":\"上海市杨浦区江浦路1000号\",\"merge\":[0,2],\"style\":29},\"2\":{\"style\":30},\"3\":{\"style\":30}}},\"5\":{\"cells\":{\"0\":{\"text\":\"所属街道\",\"style\":20},\"1\":{\"text\":\"xx路xx街道\",\"style\":29},\"2\":{\"text\":\"身份证号\",\"style\":20},\"3\":{\"style\":29,\"text\":\"3451904234242352566\"}}},\"6\":{\"cells\":{\"0\":{\"merge\":[6,0],\"text\":\"工作经历\",\"style\":16},\"1\":{\"text\":\"开始结束年月\",\"style\":20},\"2\":{\"text\":\"公司名称\",\"style\":20},\"3\":{\"text\":\"部门及职务\",\"style\":20},\"5\":{\"style\":24}}},\"7\":{\"cells\":{\"0\":{\"style\":17},\"1\":{\"text\":\"2020.1-至今\",\"style\":29},\"2\":{\"text\":\"安吉加加\",\"style\":29},\"3\":{\"text\":\"工程研发部\",\"style\":29}}},\"8\":{\"cells\":{\"0\":{\"style\":17},\"1\":{\"text\":\"2020.1-至今\",\"style\":29},\"2\":{\"text\":\"安吉加加\",\"style\":29},\"3\":{\"text\":\"工程研发部\",\"style\":29}}},\"9\":{\"cells\":{\"0\":{\"style\":17},\"1\":{\"text\":\"2020.1-至今\",\"style\":29},\"2\":{\"text\":\"安吉加加\",\"style\":29},\"3\":{\"text\":\"工程研发部\",\"style\":29}}},\"10\":{\"cells\":{\"0\":{\"style\":17},\"1\":{\"text\":\"2020.1-至今\",\"style\":29},\"2\":{\"text\":\"安吉加加\",\"style\":29},\"3\":{\"text\":\"工程研发部\",\"style\":29}}},\"11\":{\"cells\":{\"0\":{\"style\":17},\"1\":{\"style\":29},\"2\":{\"style\":29},\"3\":{\"style\":29}}},\"12\":{\"cells\":{\"0\":{\"style\":17},\"1\":{\"style\":29},\"2\":{\"style\":29},\"3\":{\"style\":29}}},\"13\":{\"cells\":{\"0\":{\"merge\":[5,0],\"text\":\"教育经历\",\"style\":18},\"1\":{\"text\":\"开始结束时间\",\"style\":20},\"2\":{\"text\":\"院校\",\"style\":20},\"3\":{\"text\":\"学士学位\",\"style\":20}}},\"14\":{\"cells\":{\"0\":{\"style\":19},\"1\":{\"text\":\"2020.1-2024.9\",\"style\":29},\"2\":{\"style\":29,\"text\":\"哈佛\"},\"3\":{\"style\":29,\"text\":\"博士\"}}},\"15\":{\"cells\":{\"0\":{\"style\":19},\"1\":{\"style\":29},\"2\":{\"style\":29},\"3\":{\"style\":29}}},\"16\":{\"cells\":{\"0\":{\"style\":19},\"1\":{\"style\":29},\"2\":{\"style\":29},\"3\":{\"style\":29}}},\"17\":{\"cells\":{\"0\":{\"style\":19},\"1\":{\"style\":29,\"merge\":[1,2]},\"2\":{\"style\":30},\"3\":{\"style\":30}}},\"18\":{\"cells\":{\"0\":{\"style\":19},\"1\":{\"style\":30},\"2\":{\"style\":30},\"3\":{\"style\":30}}},\"19\":{\"cells\":{\"0\":{\"merge\":[3,0],\"style\":31,\"text\":\"您是否具有、并愿意提供市场化业务渠道\"},\"1\":{\"style\":29,\"merge\":[3,2]}}},\"20\":{\"cells\":{\"0\":{\"style\":33}}},\"21\":{\"cells\":{\"0\":{\"style\":33}}},\"22\":{\"cells\":{\"0\":{\"style\":33}}},\"23\":{\"cells\":{\"0\":{\"merge\":[2,0],\"style\":31,\"text\":\"希望您提供的信息\"},\"1\":{\"merge\":[2,2],\"style\":29},\"2\":{\"style\":30},\"3\":{\"style\":30}}},\"24\":{\"cells\":{\"0\":{\"style\":33},\"1\":{\"style\":29},\"2\":{\"style\":29},\"3\":{\"style\":29}}},\"25\":{\"cells\":{\"0\":{\"style\":33},\"1\":{\"style\":29},\"2\":{\"style\":29},\"3\":{\"style\":29}}},\"26\":{\"cells\":{\"0\":{\"merge\":[1,3],\"text\":\"本人承诺，以上信息均属事实，若有不实，本人自愿承担相应后果。\",\"style\":30},\"1\":{\"style\":30},\"2\":{\"style\":30},\"3\":{\"style\":30}}},\"27\":{\"cells\":{\"0\":{\"style\":30},\"1\":{\"style\":30},\"2\":{\"style\":30},\"3\":{\"style\":30}}},\"28\":{\"cells\":{\"0\":{\"style\":30},\"1\":{\"style\":30},\"2\":{\"text\":\"签名：\",\"style\":34},\"3\":{\"style\":30}}},\"29\":{\"cells\":{\"0\":{\"style\":30},\"1\":{\"style\":30},\"2\":{\"text\":\"日期：\",\"style\":34},\"3\":{\"style\":30}}},\"len\":100},\"cols\":{\"0\":{\"width\":98},\"1\":{\"width\":164},\"2\":{\"width\":73},\"3\":{\"width\":234},\"len\":52},\"validations\":[],\"autofilter\":{}}";

        JSONObject jsonObject = JSONObject.parseObject(str);
        JSONArray jsonArray = jsonObject.getJSONArray("QRCodeOrBarCode");
        XSSFWorkbook workbook = new XSSFWorkbook();
        XSSFSheet sheet = workbook.createSheet();

        GaeaReportExcelUtil.makePhoto(jsonArray , workbook , sheet);

        workbook.write(new FileOutputStream("E:\\excel\\e\\l.xlsx"));

    }


}
